package com.atyoung.youngmall.product.service.impl;

import com.atyoung.youngmall.product.dao.BrandDao;
import com.atyoung.youngmall.product.dao.CategoryDao;
import com.atyoung.youngmall.product.entity.BrandEntity;
import com.atyoung.youngmall.product.service.BrandService;
import com.atyoung.youngmall.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atyoung.common.utils.PageUtils;
import com.atyoung.common.utils.Query;

import com.atyoung.youngmall.product.dao.CategoryBrandRelationDao;
import com.atyoung.youngmall.product.entity.CategoryBrandRelationEntity;
import com.atyoung.youngmall.product.service.CategoryBrandRelationService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;
    @Autowired
    private BrandDao brandDao;
    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private BrandService brandService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveDetail(CategoryBrandRelationEntity categoryBrandRelation) {
        Long brandId = categoryBrandRelation.getBrandId();
        Long catelogId = categoryBrandRelation.getCatelogId();
        String brandName = brandDao.selectById(brandId).getName();
        String catelogName = categoryDao.selectById(catelogId).getName();
        categoryBrandRelation.setBrandName(brandName);
        categoryBrandRelation.setCatelogName(catelogName);
        categoryBrandRelationDao.insert(categoryBrandRelation);
    }

    @Override
    public List<BrandEntity> getBrandsList(Long catId) {
        List<CategoryBrandRelationEntity> list = categoryBrandRelationDao.selectList(
                new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id",catId));
       List<BrandEntity> brandEntityList = list.stream().map( entity -> {
            Long brandId = entity.getBrandId();
            BrandEntity brandEntity = brandService.getById(brandId);
            return brandEntity;
        }).collect(Collectors.toList());
        return brandEntityList;
    }
}